package com.mytest.utils;

import com.mytest.filter.TPMonitorFilter;

import java.util.*;
import java.util.stream.Collectors;

public class CountTime implements Runnable {
    @Override
    public void run() {
        System.out.println("1分钟内每个方法的TP90、TP99的耗时情况");
        Map<String, Set<TPMonitorFilter.MessageInfo>> requestTime = TPMonitorFilter.REQUEST_TIME;
        //遍历集合
        int count = 0;
        Set<Map.Entry<String, Set<TPMonitorFilter.MessageInfo>>> entries = requestTime.entrySet();
        for (Map.Entry<String, Set<TPMonitorFilter.MessageInfo>> entry : entries) {
            //获得各个方法sayHelloA、sayHelloB、sayHelloC的MessageInfo统计集合对象
            Set<TPMonitorFilter.MessageInfo> values = entry.getValue();
            count += values.size();
            //计算TP90、TP99性能指标
            System.out.println(entry.getKey()+"的TP90指标耗时为"+getTPquota(values,0.90)+"ms, TP99指标耗时为"+getTPquota(values,0.99)+"ms");
        }
        System.out.println("1分钟内3个方法共被调用"+count+"次\n");
    }

    private long getTPquota(Set<TPMonitorFilter.MessageInfo> messageInfos,double tpVal){
        try {
            //获取当前前一分钟的时间戳
            long oneMinuteTimeMill = System.currentTimeMillis() - 60000;

            //移除集合中离最近1分钟内过时的数据
            messageInfos.removeIf(m->m.getEndTime()<=oneMinuteTimeMill);
            //删除时索引改变，指针移动的时候找不到对象，需要重新排序并转list集合
            List<TPMonitorFilter.MessageInfo> collect = messageInfos.stream().sorted().collect(Collectors.toList());
            //TP指标耗时
            int size = collect.size();
            int index = (int) Math.ceil(size * tpVal);
            TPMonitorFilter.MessageInfo messageInfo = collect.get(index - 1);
            return messageInfo.getTime();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
